package com.grj.template.boot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grj.template.boot.domain.R;
import com.grj.template.boot.domain.User;
import com.grj.template.boot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import static cn.hutool.json.JSONUtil.toBean;

@Api(tags = "用户管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    /**
     * 分页查询用户列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param user 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation("分页查询用户列表")
    @PreAuthorize("hasAuthority('user:page')")
    public R<Page<User>> fetchUserPage(
            @RequestParam int currentPage,
            @RequestParam int pageSize,
            @RequestParam String user,
            @RequestParam(required = false) List<Date> during
    ) {
        return R.ok(userService.fetchUserPage(currentPage, pageSize, toBean(user, User.class), during));
    }

    /**
     * 添加用户
     * @param user 用户对象
     * @return 添加结果
     */
    @PostMapping
    @ApiOperation("添加用户")
    @PreAuthorize("hasAuthority('user:post')")
    public R<Void> postUser(@RequestBody @Valid User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.postUser(user);
        return R.okMsg("添加用户成功");
    }

    /**
     * 更新用户
     * @param user 用户对象
     * @return 更新结果
     */
    @PutMapping
    @ApiOperation("更新用户")
    @PreAuthorize("hasAuthority('user:put')")
    public R<Void> putUser(@RequestBody @Valid User user) {
        userService.putUser(user);
        return R.okMsg("更新用户成功");
    }

    /**
     * 删除用户
     * @param userId 用户 ID
     * @return 删除结果
     */
    @DeleteMapping("/{userId}")
    @ApiOperation("删除用户")
    @PreAuthorize("hasAuthority('user:delete')")
    public R<Void> delUser(@PathVariable Long userId) {
        userService.delUser(userId);
        return R.okMsg("删除用户成功");
    }

    /**
     * 批量删除用户
     * @param userIds 用户 ID 数组
     * @return 删除结果
     */
    @DeleteMapping("/batch/delete")
    @ApiOperation("批量删除用户")
    @PreAuthorize("hasAuthority('user:batch:delete')")
    public R<Void> batchDelUser(@RequestParam List<Long> userIds) {
        userService.batchDelUser(userIds);
        return R.okMsg("批量删除用户成功");
    }

    /**
     * 获取用户详情
     * @param id 用户 ID
     * @return 用户详情
     */
    @GetMapping("/{id}")
    @ApiOperation("获取用户详情")
    @PreAuthorize("hasAuthority('user:get')")
    public R<User> fetchUserById(@PathVariable Long id) {
        return R.ok(userService.fetchUserById(id));
    }

    /**
     * 获取当前用户信息
     * @return 当前用户信息
     */
    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    public R<User> getCurrentUserInfo() {
        User user = userService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        user.setPassword(""); // 不返回密码
        return R.ok(user);
    }

    /**
     * 导出用户数据
     * @param response 响应对象
     * @throws IOException IO异常
     */
    @GetMapping("/export")
    @ApiOperation("导出用户数据")
    @PreAuthorize("hasAuthority('user:export')")
    public void exportData(HttpServletResponse response) throws IOException {
        List<User> userList = userService.list();
        StringBuilder csvContent = new StringBuilder();
        userList.forEach(user -> {
            csvContent.append(user.getUserId()).append(",")
                    .append(user.getUsername()).append(",")
                    .append(user.getStatus()).append(",")
                    .append(user.getCreateTime()).append(",")
                    .append(user.getUpdateTime()).append("\n");
        });
        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()) + ".csv";
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/csv");
        response.getWriter().write(csvContent.toString());
    }

    /**
     * 导入用户数据
     * @param file CSV文件
     * @return 导入结果
     * @throws IOException IO异常
     */
    @PostMapping("/upload")
    @ApiOperation("导入用户数据")
    @PreAuthorize("hasAuthority('user:import')")
    public R<Void> upload(@RequestParam("file") MultipartFile file) throws IOException {
//        List<User> userList = SecurityUtil.parseCsv(file.getInputStream(), User.class);
//        for (User user : userList) {
//            user.setPassword(passwordEncoder.encode(user.getPassword()));
//        }
//        userService.saveBatch(userList);
        return R.okMsg("导入用户成功");
    }
}

